package com.br.aiops.alert.config;

import com.br.aiops.alert.config.db.ReceiverService;
import com.br.aiops.counter.AlertLogCounter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class ReceiverCache {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReceiverCache.class);

    public static final int RECEIVER_TYPE_PERSON = 0;
    public static final int RECEIVER_TYPE_GROUP = 1;

    @Autowired
    private ReceiverService receiverService;

    //按人接收
    private Map<String, List<Receiver>> receiverByPerson = Maps.newConcurrentMap();

    //按组接收
    private Map<String, List<Receiver>> receiverByGroup = Maps.newConcurrentMap();

    @Scheduled(fixedDelay = 120 * 1000)
    private void load() {
        try {
            //加载按人接收人
            receiverByPerson = receiverService.getReceiverByPerson()
                    .parallelStream()
                    .filter(receiver -> Objects.nonNull(receiver.getRuleId()))
                    .collect(Collectors.groupingByConcurrent(Receiver::getRuleId));

            //加载按组接收人
            receiverByGroup = receiverService.getReceiverByGroup()
                    .parallelStream()
                    .filter(receiver -> Objects.nonNull(receiver.getRuleId()))
                    .collect(Collectors.groupingByConcurrent(Receiver::getRuleId));
            LOGGER.info("缓存加载完成。");
        } catch (Exception e) {
            LOGGER.error("加载缓存失败，但缓存依然可用。", e);
        }
    }

    public Map<String, List<Receiver>> getReceiverByPerson() {
        return receiverByPerson;
    }

    public Map<String, List<Receiver>> getReceiverByGroup() {
        return receiverByGroup;
    }

    public List<Receiver> getReceiverConfigs(AlertLogCounter counter) {
        switch (counter.getRule().getReceiverType()) {
            case RECEIVER_TYPE_PERSON:
                return receiverByPerson.getOrDefault(counter.getRule().getRuleUuid(), Lists.newArrayList());
            case RECEIVER_TYPE_GROUP:
                return receiverByGroup.getOrDefault(counter.getRule().getRuleUuid(), Lists.newArrayList());
            default:
                throw new RuntimeException("未支持的接收类型；接收类型必须是0或者1");
        }
    }
}
